package com.example.xm.service.impl;
import com.example.xm.entity.Cartentity;
import com.example.xm.entity.Productentity;
import com.example.xm.entity.vo.CartListVo;
import com.example.xm.exception.SerceiceException;
import com.example.xm.mapper.CartMapper;
import com.example.xm.mapper.ProductMapper;
import com.example.xm.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author tong
* @description 针对表【cart】的数据库操作Service实现
* @createDate 2024-04-13 12:37:40
*/
@Service
public class CartServiceImpl implements CartService {
@Autowired(required = false)
    CartMapper cartMapper;
@Autowired(required = false)
    ProductMapper productMapper;
    @Override
    public void add(Cartentity cartentity) {
       Cartentity cartentity1= cartMapper.selectCart(cartentity.getUserId(),cartentity.getProductId());
       if(cartentity1!=null){
           Productentity byId = productMapper.getById(cartentity.getProductId());
           if(cartentity1.getCount()>=byId.getKucun()){
               throw new SerceiceException(400,"库存不足");
           }
           Cartentity cartentity2 = new Cartentity();
           cartentity2.setId(cartentity1.getId());
           cartentity2.setCount(cartentity1.getCount()+1);
           cartMapper.updateByPrimaryKeySelective(cartentity2);
       }else{
           cartMapper.insert(cartentity);
       }
    }

    @Override
    public List<CartListVo> list(Cartentity cartentity) {
        return cartMapper.list(cartentity);
    }

    @Override
    public void update(Cartentity cartentity) {
        cartMapper.updateByPrimaryKeySelective(cartentity);
    }

    @Override
    public void deleteById(Integer id) {
        cartMapper.deleteById(id);
    }
}




